﻿namespace EyeOpen.Services.Services
{
	using System;
	using System.Linq;
	using System.Web.Mvc;
	using EyeOpen.Domain;
	using EyeOpen.Mvc.Models;

	[Authorize]
	public class BackEndController : Controller
	{
		private readonly IWebSiteService webSiteService;

		public BackEndController()
			: this(new WebSiteService())
		{
		}

		public BackEndController(IWebSiteService webSiteService)
		{
			this.webSiteService = webSiteService;
		}

		public ActionResult Index()
		{
			var contentLocalizedList =
				webSiteService
					.GetContentLocalizedList();
				
			var pathViewModelList =
				contentLocalizedList
					.OrderBy(x => x.Order)
					.Select(x => new SectionViewModel { Id = x.Id, Text = x.Text, Title = x.Title, Path = x.Path, Language = x.Language.TwoLetter })
					.ToList();

			var contentLocalizedViewModel = new ContentLocalizedViewModel(contentLocalizedList.Single(c => c.Path == null));

			return View(new ContentLocalizedEditingViewModel(pathViewModelList, contentLocalizedViewModel));
		}

		[ValidateInput(false)]
		public ActionResult Edit(Guid id)
		{
			var contentLocalizedList =
				webSiteService
					.GetContentLocalizedList();
				
			var contentLocalizedViewModel = new ContentLocalizedViewModel(contentLocalizedList.Single(c => c.Id == id));

			return View("Detail", contentLocalizedViewModel);
		}

		[ValidateInput(false)]
		public ActionResult Save(ContentLocalizedViewModel contentLocalizedViewModel)
		{
			if (!ModelState.IsValid)
			{
				return View("Detail");
			}

			webSiteService
				.Update(
					new ContentLocalized
						{
							Id = contentLocalizedViewModel.Id,
							Title = contentLocalizedViewModel.Title,
							Description = contentLocalizedViewModel.Description,
							Keywords = contentLocalizedViewModel.Keywords,
							Body = contentLocalizedViewModel.Body
						});

			contentLocalizedViewModel.Saved = true;

			return View("Detail", contentLocalizedViewModel);
		}
	}
}